import http.client
import hashlib
import urllib
import random
import json


class Bdfy():
    def __init__(self):
        self.appid = '20180819000195991'
        self.secretKey = 'IyjzDKYK3N_mdHL4tpe7'
        self.httpClient = None
        self.myurl = '/api/trans/vip/translate'
        self.fromLang = 'en'
        self.toLang = 'zh'
        self.q=''

    def setSign(self):
        salt = random.randint(32768, 65536)
        sign = self.appid + self.q + str(salt) + self.secretKey
        sign = hashlib.md5(sign.encode()).hexdigest()
        self.myurl = self.myurl + '?appid=' + self.appid + '&q=' + urllib.parse.quote(
            self.q) + '&from=' + self.fromLang + '&to=' + self.toLang + '&salt=' + str(
            salt) + '&sign=' + sign

    def doFy(self):
        # try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', self.myurl)
        # response是HTTPResponse对象
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
        trans_result = result['trans_result']
        res = ''
        for i in trans_result:
            if 'dst' in i.keys():
                res = res+i['dst']
        # except Exception as e:
        #     print(e)
        #     return self.q
        # finally:
        if httpClient:
            httpClient.close()
        return res

    def zhToen(self,q):
        self.fromLang = 'zh'
        self.toLang = 'en'
        self.q = q
        self.setSign()
        return self.doFy()

    def enTozh(self,q):
        self.fromLang = 'en'
        self.toLang = 'zh'
        self.q = q
        self.setSign()
        return self.doFy()

